package com.lw.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.wxpay.sdk.WXPayUtil;

import com.lw.commonutil.result.ResultCodeEnum;
import com.lw.order.entity.MemberCourse;
import com.lw.order.entity.Order;
import com.lw.order.entity.PayLog;
import com.lw.order.mapper.MemberCourseMapper;
import com.lw.order.mapper.PayLogMapper;
import com.lw.order.service.OrderService;
import com.lw.order.service.PayLogService;
import com.lw.order.utils.ConstantPropertiesUtils;
import com.lw.order.utils.HttpClient;
import com.lw.servicebase.exception.GuliException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class PayLogServiceImpl extends ServiceImpl<PayLogMapper, PayLog> implements PayLogService {

    @Autowired
    private OrderService orderService;
    @Autowired
    private MemberCourseMapper memberCourseMapper;
    //生成支付二维码
    @Override
    public Map<String, Object> createNative(String orderNo) {
        try {
            //根据订单号查询订单信息
            QueryWrapper<Order> wrapper = new QueryWrapper<>();
            wrapper.eq( "order_no", orderNo );
            Order order = orderService.getOne( wrapper );
            //使用map设置生成二维码参数
            Map<String,String> m =new HashMap<>();
            m.put("appid", ConstantPropertiesUtils.APPID );
            m.put("mch_id", ConstantPropertiesUtils.PARTNER);
            m.put("nonce_str", WXPayUtil.generateNonceStr());
            m.put("body", order.getCourseTitle());
            m.put("out_trade_no", orderNo);//订单号
            m.put("total_fee", order.getTotalFee().multiply(new BigDecimal("100")).longValue()+"");
            m.put("spbill_create_ip", "127.0.0.1");
            m.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify");//没用的
            m.put("trade_type", "NATIVE");
            //发送httpClient请求
            HttpClient client = new HttpClient( "https://api.mch.weixin.qq.com/pay/unifiedorder" );
            //设置xml参数
            client.setXmlParam( WXPayUtil.generateSignedXml( m,ConstantPropertiesUtils.PARTNERKEY ) );
            client.setHttps( true ); //设置支持https请求
            client.post();
            //得到返回结果
            //返回内容为xml格式
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap( xml );

            //最终返回数据的封装
            Map<String,Object> map = new HashMap();
            map.put("out_trade_no", orderNo);
            map.put("course_id", order.getCourseId());
            map.put("total_fee", order.getTotalFee());
            map.put("result_code", resultMap.get("result_code")); //状态码
            map.put("code_url", resultMap.get("code_url")); //二维码地址
            return map;
        }catch (Exception e){
            throw new GuliException( ResultCodeEnum.FAIL );
        }
    }

    //查询支付状态
    @Override
    public Map<String, String> queryPayStatus(String orderNo) {
        try {
            //1、封装参数
            Map m = new HashMap<>();
            m.put("appid", ConstantPropertiesUtils.APPID);
            m.put("mch_id", ConstantPropertiesUtils.PARTNER);
            m.put("out_trade_no", orderNo);
            m.put("nonce_str", WXPayUtil.generateNonceStr());
            //2、设置请求
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(m, ConstantPropertiesUtils.PARTNERKEY));
            client.setHttps(true);
            client.post();
            //3、返回第三方的数据
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            return resultMap;
        }catch (Exception e){
            throw new GuliException( ResultCodeEnum.FAIL );
        }
    }

    //更新订单状态和添加支付记录表
    @Override
    public void updateOrderStatus(Map<String, String> map) {
        try {
            //从map获取订单号
            String orderNo = map.get( "out_trade_no" );
            //根据订单号查询订单信息
            QueryWrapper<Order> wrapper =new QueryWrapper<>();
            wrapper.eq( "order_no",orderNo );
            Order order = orderService.getOne( wrapper );
            if (order.getStatus().intValue()==1){
               return;
            }
            //更新订单支付状态
            order.setStatus( 1 );
            orderService.updateById( order );
            //向支付记录表中添加记录
            PayLog payLog = new PayLog();
            payLog.setOrderNo(order.getOrderNo());//支付订单号
            payLog.setPayTime(new Date());
            payLog.setPayType(1);//支付类型 微信
            payLog.setTotalFee(order.getTotalFee());//总金额(分)
            payLog.setTradeState(map.get("trade_state"));//支付状态
            payLog.setTransactionId(map.get("transaction_id"));//流水号
            payLog.setAttr( JSONObject.toJSONString(map));
            baseMapper.insert( payLog );
            //向会员课程表中添加购买记录
            MemberCourse memberCourse = new MemberCourse();
            memberCourse.setMemberId( order.getMemberId() );
            memberCourse.setCourseId( order.getCourseId() );
            memberCourse.setOrderNo( orderNo );
            memberCourseMapper.insert( memberCourse );
        }catch (Exception e){ //使用try catch事务不会回滚，需要手动回滚或者抛出运行时异常
            //手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            //进行多次重试或者退款
            this.updateOrderStatus( map );//多次重试
        }
    }
}
